import { common } from '../../services/index.js'
import config from '../../config/index.js'
// 含有示例文字 和白色底图
const boradBgImg = require('../../utils/data.js').boradBgImg
// 不含任何文字  和白色底
const imgUrls = require('../../utils/data.js').tmpImgUrls_new
// 截切字符串
const clipStr = require('./clipStr.js')

var app = getApp()
// component/tip/tip.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    isLoading :{
      type :Boolean ,
      value : true 
    },
    mode :{
      // 1 示例图 2 模版场景图 3 定制图 4 本地上传
      type : Number ,
      value : 1
    },
    textAreaStr :{
      type : String,
      value: ''
    },
    textAreaTmp:{
      type: String,
      value: ''
    },
    createFlag : {
      type: Number,
      value: -1,
      observer: function (newVal, oldVal) {
        this.preData(this.data.flag)
      }
    },
    photoFile: {
      type: String ,
      value : ''
    },
    flag: { // 生成日签标志
      type: Number,
      value: -1,
      observer: function (newVal, oldVal) {
        this.preData(newVal)
        return 
        if( this.data.gather.indexOf(newVal) > -1 ){
          console.log('已生成过》》 flag: ' + newVal)
        }else{
          if (!this.data.hasCreated) {
            this.preData(newVal)
          } else {
            if (this.data.isLoading) {
              wx.showToast({
                title: '正在生成日签...',
                icon: 'loading',
                duration: 2000
              })
            }
            this.createYearCard(newVal)
          }
          
        }
      }
    }
  },
  data:{
    headImg: 'https://image.artyears.cn/template/defaultHeadImg.png?imageView2/1/w/80/h/80/q/30',
    qrcode: '' ,
    sysInfo: app.globalData.sysInfo ,
    months : ['一','二','三','四','五','六','七','八','九','十','十一','十二'],
    rate : '' ,
    qrcodeUrl : '' ,
    isShowDialog: false ,
    // 头像
    headImgUrl: '',
    // 用户名
    userName: '',
    createTime: (+new Date()),
    activityName: '',
    activityId: 0,
    // 坚持人数
    insistDay: 0,
    creator: 0, // 0 或者1 是否
    shareCardUrl: null  ,
    // 是否有生成过日签，不用再下载 头像和二维码
    hasCreated: false ,
    // 已生成过的图片集合
    gather : []
  },
  ready(){
    //this.preData()
    var _self = this
    var daySignData = wx.getStorageSync('daySign')
    this.setData({
      headImgUrl: daySignData.headImgUrl,
      userName: daySignData.userName,
      createTime: Number(daySignData.createTime),
      activityName: daySignData.activityName,
      activityId: daySignData.activityId,
      insistDay: daySignData.insistDay,
      momentId: daySignData.momentId ,
      creator: daySignData.creator == '0'? 0 : 1,
      skipAppId: daySignData.skipAppId
    })
    console.log({
      headImgUrl: daySignData.headImgUrl,
      userName: daySignData.userName,
      createTime: Number(daySignData.createTime),
      activityName: daySignData.activityName,
      activityId: daySignData.activityId,
      insistDay: daySignData.insistDay,
      momentId: daySignData.momentId,
      creator: daySignData.creator == '0' ? 0 : 1,
      skipAppId: daySignData.skipAppId
    })
  },
  /**
   * 组件的方法列表
   */
  methods: {
    myEventListener(){
      wx.showToast({
        title: 'xiaodsaf',
      })
      this.preData()
    },
    preData(current){
      var _self = this
      var daySignData = wx.getStorageSync('daySign')
      this.setData({
        headImgUrl: daySignData.headImgUrl,
        userName: daySignData.userName,
        createTime: Number(daySignData.createTime),
        activityName: daySignData.activityName,
        activityId: daySignData.activityId,
        insistDay: daySignData.insistDay,
        momentId: daySignData.momentId,
        creator: daySignData.creator == '0' ? 0 : 1,
        skipAppId: daySignData.skipAppId
      })
      if (this.data.isLoading){
        wx.showToast({
          title: '正在生成日签...',
          icon: 'loading',
          duration: 2000
        })
      }
      var that = this
      var dateObj = new Date(this.data.createTime)
      var month = dateObj.getMonth() + 1 < 10 ? '0' + (dateObj.getMonth() + 1) : (dateObj.getMonth() + 1)
      var dateStr = dateObj.getFullYear() + '-' + month + '-' + (dateObj.getDate() < 10 ? '0' + dateObj.getDate() : dateObj.getDate())
      var paramsObj = {
        id: this.data.activityId ,
        mId : this.data.momentId ,
        d: dateStr
      }
      var scene = 'id=' + this.data.activityId + '&mId=' + this.data.momentId + '&d=' + dateStr
      console.log( scene )
      console.log('id=' + this.data.activityId + '&momentId=' + this.data.momentId + '&date=' + dateStr )
      
      common.createMiniQRCode({
        //appId: config.appid ,
        appId: this.data.skipAppId ,
        pages: 'pages/attendancePreview/attendancePreview',
        scene: scene,
        width : 174 
      }).then(res=>{
        console.log('获取二维码成功', res)
        wx.downloadFile({
          url: app.globalData.prefix + res.data.qrCodeUrl ,
          success: function (res) {
            that.setData({
              qrcodeUrl :  res.tempFilePath
            }) 
            wx.downloadFile({
              //url: that.data.headImg,
              url: that.data.headImgUrl,
              success: function (res) {
                // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
                if (res.statusCode === 200) {
                  that.setData({
                    headImg: res.tempFilePath
                  })
                  that.createYearCard(current)
                }
              },
            })
          }
        })
      })
    },
    createYearCard: function(cid) {
      const index = cid
      var that = this 
      var calendarTextColor = '#ffffff'
      var boardPath 
      if(this.data.mode == 1){
        boardPath = boradBgImg[cid]
      } else if (this.data.mode == 2 || this.data.mode == 3 ){
        boardPath = imgUrls[cid]
      } else{
        // 照片本地上传
        boardPath = this.data.photoFile
      }
      var sysInfo = this.data.sysInfo
      console.log(sysInfo)
      var screenWidth = sysInfo.windowWidth
      var screenHeight = sysInfo.windowHeight 
      var rate = (screenWidth / 750)
      that.setData({
        rate 
      })
      var boardW = rate * 700 // rpx => px
      var boardH = rate * 1210 // rpx => px
      const context = wx.createCanvasContext('myphoto',that);
      
      
      // 生成背景图
      console.log(boardW, boardH)
      context.drawImage(boardPath, 0, 0, boardW, boardH)
      if (this.data.mode != 1) {
        var whiteBarW = 700 * rate 
        var whiteBarH = 380 * rate 
        var whiteBarOffsetTop = boardH - whiteBarH

        context.drawImage('../../assets/images/white.png', 0, whiteBarOffsetTop, whiteBarW, whiteBarH)
      } 
      // 二维码
      this.drawQrcode(context)
       var d = new Date(this.data.createTime)
      // // var d = new Date('2018-01-01')
      // console.log(that)
       that.drawCalendar(context, d, calendarTextColor)

      // 头像
      this.drawBottom(context)
      if( that.data.textAreaStr ){
        var centerOffsetLeft = 40 * rate
        var offsetTop = (sysInfo.windowHeight * (107 / 2)) / 1210 
        //var offsetTop = (sysInfo.windowHeight * (107 / 2)) / 1210 + outerOffsetTop
        this.drawDesc(context, screenWidth, centerOffsetLeft, offsetTop)
      }
    
      context.draw()
      //将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
      setTimeout(function () {
        wx.canvasToTempFilePath({
          canvasId: 'myphoto',
          success: function (res) {
            
            const tempFilePath = res.tempFilePath;
            console.log(tempFilePath)
            that.triggerEvent('success', {tempFilePath,index})
            wx.hideToast()
            return 
            that.setData({
              shareCardUrl: tempFilePath ,
              isShowDialog : true 
            },function(){
              wx.hideToast()
            })
          }
        },that);
      }, 500);
    }, 
    //将姓名绘制到canvas的固定
    /*
      函数说明
      画中间对输入内容
      @params {Object} context 当前canvas对象
      @params {Num} screenWidth 屏幕宽度
      @params {Num}  x ：x方向的偏移量
      @params {Num}  y ：y方向的偏移量
    */
    drawDesc: function (context, screenWidth, x, y) {
      
      var desc = this.data.textAreaStr
      var offset = ((25) / 375 * screenWidth)
      var fontSize = (21 / 375 * screenWidth)
      context.setFontSize(fontSize)
      context.setFillStyle("#ffffff")
      // context.textBaseline = "middle";
      context.save()
      // 换行分隔数组
      var rows = clipStr.autoClipTheStr(this.data.textAreaTmp)
      console.log(desc, this.data.textAreaTmp,rows)
      // 根据 换行分割 顺序画出文字换行
      clipStr.drawText(rows, x + 10 / 2, y + 209 / 2, offset, context)
      //context.fillText(desc, 63/2, 239/2);//必须为（0,0）原点
      //this.drawText(testStr, 63 / 2, 239 / 2, 502 / 750 * screenWidth ,context)    
    },
    // 左上角 日期
    drawCalendar(context, date, calendarTextColor) {
      var rate = this.data.rate
      var year = date.getFullYear().toString()
      var month = date.getMonth().toString()
      var day = date.getDate()
      var yearStr = year
      var monthStr = this.data.months[month] // 中文
      day = day< 10  ? '0' + day : day
      var dayStr = day // 中间加空格
      // 样式设置
      // 天
      context.setFontSize(80 * rate)
      context.setFillStyle(calendarTextColor)
      console.log(61 * rate)
      var baseHeight  = 60 
      context.setTextBaseline('top')
      context.fillText(dayStr, 49 * rate,   (61-25) * rate);
      context.stroke();
      // 日
      context.setFontSize(19 * rate)
      context.setFillStyle(calendarTextColor)
      var lineHeight = 15
      if( monthStr.length == 2 ){
        context.fillText(monthStr[0], (136 + 10) * rate, ( 61 - 20 ) * rate);
        context.fillText(monthStr[1], (136 + 10) * rate, (61 - 20 + 19 + lineHeight) * rate)
        context.fillText('月', (136 + 10)  * rate, (61 - 20 + 19 + 19 + lineHeight *2) * rate);
      }
      else{
        context.fillText(monthStr, (136 + 10)  * rate, ( 54 + 5 ) * rate);
        context.fillText('月', (136 + 10)  * rate, (baseHeight + 19 + lineHeight) * rate);
      }
      context.stroke();
      // 下划线
      this.drawLine(context, calendarTextColor)
      // 年
      this.setYear(yearStr ,context)
      
    },
    setYear(yearStr, context){
      var rate = this.data.rate

      context.setFontSize(28 * rate)
      //context.fillText(yearStr, 49 * rate, (147 - 10) * rate);
      for( let i = 0 ;i < yearStr.length; i++ ){
        
        context.fillText(yearStr[i], (52 + i *( 28 * rate + 18) ) * rate, (147 - 10) * rate );
        
        context.stroke();  
        
      }  
    },
    /*
    * 画下划线
    */
    drawLine(context, calendarTextColor){
      context.beginPath() 
      context.setLineWidth(1) 
      var rate = this.data.rate 
      context.moveTo(50 * rate, (137 ) * rate ) 
      context.lineTo(165 * rate, (137 ) * rate ) 
      //strokeStyle = 'rgba(255,0,0,0.5)'; 
      context.setStrokeStyle(calendarTextColor) 
      context.stroke() 
    },
    // 头像
    drawHeadImg(context){
      var rate = this.data.rate 
      context.drawImage(this.data.headImg, 40*rate, 1021 *rate, 58 * rate, 58 *rate)
    },
    drawText(context, userName ,activityName ){
      var rate = this.data.rate 
      context.setFontSize(24 * rate)
      context.setFillStyle("#080808")
      context.setTextBaseline('top')
      context.fillText(this.data.userName, 112 * rate, (1021  ) * rate);
      context.setFontSize(24 * rate)
      if (this.data.creator == '0' || this.data.creator == 0 ){
        context.fillText('坚持' + this.data.insistDay + '天打卡', 112 * rate, (1057 - 5) * rate);
      }
      
      context.stroke()
    },
    drawActivityName(context){
      const rate = this.data.rate 
      const str = this.data.activityName
      context.setFontSize(22 * rate)
      context.setFillStyle("#BDBDBD")
      context.setTextBaseline('top')
      for(let i = 0 ; i < str.length ; i++){
        // 超过字数换行
        if(i > 19){
          context.fillText(str[i], (40 + (i-20) * 43 * rate) * rate, (1100+30) * rate);  
          context.stroke()
        }else{
          context.fillText(str[i], (40 + i * 43 * rate) * rate, (1100) * rate); 
          context.stroke() 
        }
      }
    },
    drawQrcode(context){
      var rate = this.data.rate
      context.drawImage(this.data.qrcodeUrl, (543 -40) *rate, 1000*rate, 174*rate, 174*rate)
      context.stroke() 
    },
    // 画 用户信息
    drawBottom(context) {
      this.drawHeadImg(context)
      this.drawText(context)
      this.drawActivityName(context)
      //this.drawQrcode(context)
    },
    previewCard(){
      wx.previewImage({

        urls: [this.data.shareCardUrl], // 需要预览的图片http链接列表
        success: function (res) {
          console.log(res)
        },
        fail: function (res) {
          console.log(res)
        }
      })
    },
    hideDialog(){
      this.setData({
        isShowDialog: false 
      }) 
    },
    // 保存到本地
    saveCerticateAsPhoto(){
      wx.saveImageToPhotosAlbum({
        filePath: this.data.shareCardUrl ,
        success(res) {
          wx.showModal({
            title: '保存成功',
            content: '快分享给小伙伴们一起围观吧～',
            showCancel: false,
          })
        }
      })
    }
    
  }// methods
  
})
